package cn.qayy.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.dto.TaskDTO;
import cn.qayy.dto.TaskTotalDTO;
import cn.qayy.po.Task;
import cn.qayy.po.TaskTotal;
import cn.qayy.po.User;
import cn.qayy.service.ITaskService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu 
 * 季度任务管理
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/task/") 
public class TaskController {
	// 注入service     
	@Resource(name = "taskServiceImpl")
	private ITaskService taskService = null;
	
	@ResponseBody
	@RequestMapping(value = "selectForList")
	public Object selectForList(TaskDTO dto,HttpServletRequest request) {
		Msg msg = null;
		try {
			User user = (User)request.getSession().getAttribute("user");
			if(user != null && user.getAge() < 1) {
				dto.setMgr(user.getUser_name());
			}
			PageInfo<Task> pageInfo = taskService.selectBy(dto);
			msg = new Msg(Constant.SUCESSFUL_CODE,pageInfo);
		} catch(Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,e.getMessage());
		}
		return msg;
	}
	
	/**
	 * 保存或更新
	 * @param dto
	 * @param flag
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "saveOrUpdate")
	public Object saveOrUpdate(TaskDTO dto,String flag) {
		Msg msg = null;
		List<Task> list = new ArrayList<Task>();
		try {
			//封装数据
			Task task = null;
			if(flag.equals("E")) {
				task = taskService.selectByID(StringUtil.parseInt(dto.getId()));
				if(task != null) {
					task.setByDTO(dto);
					list.add(task);
					taskService.updateByList(list);
				}
			} else if(flag.equals("N")) {
				task = new Task();
				task.setByDTO(dto);
				list.add(task);
				taskService.insertByList(list);
			}
			msg = new Msg(Constant.SUCESSFUL_CODE,Constant.SUCESSFUL_MSG);
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 通过导入Excel文件，批量上传。
	 * @param excelFile，MultipartFile接收页面上传上来的Excel文件 
	 * @param request
	 * @return
	 * 1、导入的数据，可能存在新增、可能存在更新，也可能存在删除，故需要封装一个service方法持久化数据，保证都在同一个事务里。目前事务
	 * 是控制在service的方法里面，故需要把相关操作都放在某个方法里执行，才能保证多个操作在同一事务里。
	 * 2、异常：code=-1:表示运行异常，code=-2：表示验证异常
	 */
	@ResponseBody
	@RequestMapping(value = "upload")
	public Object uploadBasisList(MultipartFile excelFile,HttpServletRequest request) {
    	Msg msg = null;
		try {
			int listSize = 0;	//excel记录数
	    	int doSize = 0;	//执行成功记录数
	    	/***
	    	 * 上传的文件，通过反射把Excel每一行封装成一个对象，存在list里，最后在封装到map里，map里很清晰的存放了
	    	 * 验证不通过的数据，或者验证通过的数据，而通过的数据又进行了E、N、D等分类。
	    	 */
	    	Map<String, List<Uploadable>> map = UploadHandler.getLastData(excelFile,TaskDTO.class);
			if(map.get("fail") != null && !map.get("fail").isEmpty()) {
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
			} else {//DB持久化
				taskService.persistence(map);
				/**用户上传的总记录数**/
		    	if(map.get("totalCount") != null) {
		    		MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
		    		listSize = StringUtil.parseInt(msgInfo.getErr_num());
		    	}
				msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数："+listSize+"，总成功数："+listSize+"，请核查！");
			}
		} catch (Exception e) {
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage()+Constant.FAIL_MSG_E);
		}
		return msg;
	}
	
	
	
	/***
	 * 页面下载汇总
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "downloadTotal")
	public void downloadTotal(HttpServletRequest request, HttpServletResponse response) {
		try { 
			TaskTotalDTO dto = new TaskTotalDTO();
			User user = (User)request.getSession().getAttribute("user");
			if(user != null && user.getAge() < 1) {
				dto.setMgr(user.getUser_name());
			}
			
			List<TaskTotal> loadDataList = taskService.selectForTotal(dto);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("季度任务总表",StringUtil.listToStrArray(CollectionConstant.taskTotal_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<TaskDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(TaskDTO.class);
			String downloadPath = ExcelUtils.taskToExcelDxls("季度任务跟进表",StringUtil.listToStrArray(CollectionConstant.task_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 查询汇总
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "selectTotal")
	public Object selectTotal(TaskTotalDTO dto) {
		Msg msg = null;
		try {

			PageInfo<TaskTotal> pageInfo = taskService.selectTotal(dto);
			
			msg = new Msg(Constant.SUCESSFUL_CODE,pageInfo);
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,e.getMessage());
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value = "selectInfoBy")
	public Object selectInfoBy(TaskDTO dto) {
		Msg msg = null;
		try {
			Msg retMsg = taskService.selectInfoBy(dto);
			msg = new Msg(retMsg.getCode(),retMsg.getMsg());
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,e.getMessage());
		}
		return msg;
	}
	
	/**
	 * 保存或更新
	 * @param dto
	 * @param flag
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public Object save(TaskDTO dto) {
		Msg msg = null;
		List<Task> list = new ArrayList<Task>();
		try {
			//封装数据
			System.out.println("insertdto:"+dto);
			int ret = taskService.insert(dto);
			msg = new Msg(Constant.SUCESSFUL_CODE,Constant.SUCESSFUL_MSG);
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,e.getMessage());
		}
		return msg;
	}
	

	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui")
	public ModelAndView ui(HttpServletRequest req) {
		ServletContext context = req.getSession().getServletContext();
		ModelAndView model = new ModelAndView();
		model.addObject("packs", CollectionConstant.packs);
		model.addObject("products", CollectionConstant.products);
		model.addObject("clientLevels",CollectionConstant.clientLevels);
		
		//获取现金流项目集合
		model.setViewName("task_search");
		
		return model;
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="total_ui")
	public ModelAndView totalui(HttpServletRequest req) {
		ModelAndView model = new ModelAndView();
		model.addObject("packs", CollectionConstant.packs);
		model.addObject("products", CollectionConstant.products);
		model.addObject("clientLevels",CollectionConstant.clientLevels);
		
		//获取现金流项目集合
		model.setViewName("taskTotal_search");
		
		return model;
	}
	
}
